import { FolderOpenOutlined } from '@ant-design/icons';
import React from 'react';
import { useControllableValue } from 'ahooks';
import { Button } from 'antd';
import Input from '../Paste/Input';
import InputGroup from '../Paste/InputGroup';
import { open } from '@tauri-apps/api/dialog';
import { message } from '@tauri-apps/api/dialog';
import { desktopDir } from '@tauri-apps/api/path';
import { invoke, path } from '@tauri-apps/api';

import './index.less';

interface WorkSpaceInputProps {
  value?: string;
  onChange?: (val: string) => void;
  placeholder?: string;
  disabled?: boolean;
}

const WorkSpaceInput: React.FC<WorkSpaceInputProps> = (props) => {
  const [state, setState] = useControllableValue<string | undefined>(props, {
    defaultValue: props.value,
  });

  const { disabled = true } = props;

  const selectFile = async () => {
    const selected = (await open({
      directory: true,
      defaultPath: state || (await desktopDir()),
    })) as string;
    if (selected) {
      const filePath = await path.join(selected, 'package.json');
      const isExist = await invoke('file_exists', {
        path: filePath,
      });
      if (!isExist) {
        await message('请选择项目package.json所在目录', {
          title: '提示',
          type: 'error',
        });
      } else {
        setState(selected);
      }
    }
  };

  return (
    <InputGroup compact className="workspace-input">
      <Input
        style={{ width: 'calc(100% - 30px)' }}
        disabled={disabled}
        placeholder="请选择项目package.json所在目录"
        value={state}
        onChange={(e: any) => setState(e.target.value)}
      />
      <Button
        icon={<FolderOpenOutlined />}
        type="primary"
        className="workspace-input-file"
        onClick={selectFile}
      ></Button>
    </InputGroup>
  );
};

export default React.memo(WorkSpaceInput);
